package assignmentonepenguins

import grails.plugin.jms.Queue
import grails.plugin.jms.Subscriber

class ListingService {
    boolean transactional = true
    def jmsService
    static exposes = ['jms']

    def mailService

    def createListing(def params) {
        Listing listing = new Listing(params)
        listing.setCreatedBy()
        [listingInstance: new Listing(params)]

    }

    def sendEmail(String email, String subjectMessage, String bodyMessage) {
        mailService.sendMail {
            to email
            from "vikas.ait@gmail.com"
            subject subjectMessage
            body bodyMessage
        }
    }

    def isListingExpired(Listing listing) {
        if (listing.getEndDate() <= new Date()) {
            jmsService.send(queue: 'listing.queue', listing.id)
            return true
        }
        else
            return false
    }

    @Queue(name = 'listing.queue')
    def createMessage(jmsMessage) {
        Listing listing = Listing.findById(jmsMessage)
        jmsService.send(topic: 'msgevent', [body: jmsMessage])
        System.out.print("Queue: Listing : " + jmsMessage + " added to the queue for expiry.")
    }

    @Subscriber(topic = "msgevent")
    def somethingHappened(msg) {
        Listing listing = Listing.findById(msg['body'])
        listing.setExpired(true)
        if (listing.getBiddings().size() != 0) {
            listing.setWinner(findWinner(listing))
        }
        listing.setEndDate(new Date())
        listing.save(flush: true)
        Thread.sleep(1000)
        listing.refresh()
        assert listing.expired == true
        sendEmail(listing)
        System.out.print("Subscriber: Listing: " + msg + " received by the subscriber and set to expired.")
    }

    def sendEmail(Listing listing) {

        def sellerEmail = Customer.findById(listing.getSeller().id).email
        sendEmail(sellerEmail, "Your item has been sold. " + listing.name, "Congratulations, item sold")
        Thread.sleep(1000)
        if (listing.getBiddings().size() != 0) {
            def winnerEmail = Customer.findById(listing.getWinner().id).email
            sendEmail(winnerEmail, "You won the bid for item: " + listing.name, "Congratulations, you won")
        }
    }

    def findWinner(Listing listing) {

        Customer bidder = listing.getBiddings().sort {x, y -> y.amount.compareTo(x.amount)}.get(0).bidder
        return bidder
    }

}
